package com.leyou.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.pojo.Cart;
import com.leyou.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String KEY_PREFIX = "ly:cart:uid:";

    @Override
    public void addCart(Cart cart) {
        //用户登录后,从Redis中获取购物车的信息,每个用户有他自己的购物车,
        // 每个购物车中的每件商品又有自己的skuId,key都需要是string类型
        Long userId = cart.getUserId();
        //根据用户的id获取到这个用户的redis信息，boundHashOps就是我们第二层map
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        //对应的skuId，对应的string的json值，有可能为空
        Object value = boundHashOps.get(cart.getSkuId().toString());
        //null放在前面避免空指针异常
        if (null == value) {
            //为空,商品第一次添加
            boundHashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
        } else {
            //将已经存在Redis中的取出来
            Cart redisCart = JsonUtils.nativeRead(value.toString(), new TypeReference<Cart>() {
            });
            redisCart.setNum(redisCart.getNum() + cart.getNum());
            //覆盖保存
            boundHashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(redisCart));
        }

    }

    @Override
    public List<Cart> queryCartByUserId(Long userId) {
        //根据用户的id获取到这个用户的redis信息，boundHashOps就是我们第二层map
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        List<Object> values = boundHashOps.values();
        List<Cart> cartList = new ArrayList<>();
        if (null != values) {
            for (Object value : values) {
                cartList.add(JsonUtils.nativeRead(value.toString(), new TypeReference<Cart>() {
                }));
            }
            return cartList;
        }
        return null;
    }

    @Override
    public void incrementCart(Cart cart) {
        updateTotalCart(cart);
    }

    private void updateTotalCart(Cart cart) {
        Long userId = cart.getUserId();
        //根据用户的id获取到这个用户的redis信息，boundHashOps就是我们第二层map
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        Object skuJson = boundHashOps.get(cart.getSkuId().toString());
        if (null != skuJson) {
            //转换为对象
            Cart cartRedis = JsonUtils.nativeRead(skuJson.toString(), new TypeReference<Cart>() {
            });
            cartRedis.setNum(cart.getNum());
            boundHashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cartRedis));
        }
    }

    @Override
    public void decrementCart(Cart cart) {
        updateTotalCart(cart);
    }

    @Override
    public void deleteCart(Long userId, Long skuId) {
        //根据用户的id获取到这个用户的redis信息，boundHashOps就是我们第二层map
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        boundHashOps.delete(skuId.toString());
    }
}
